﻿using IoTPowerExample;
using System.Drawing;
using System.Runtime.InteropServices;
using Console = Colorful.Console;

//提高优先级
var prop = System.Diagnostics.Process.GetCurrentProcess();
prop.PriorityClass = System.Diagnostics.ProcessPriorityClass.RealTime;

//检查下dll在不在
try
{
    Device.iot_get_class();
}
catch
{
    var dll = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "iot_uart.dll" : 
        (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "libiot_uart.so" : "libiot_uart.dylib");
    Console.WriteLine($"缺少文件{dll}，请将其置于可执行文件同级目录下，并保证文件名正确", Color.Red);
    return;
}

//新建设备对象
var device = new Device();

//列一下现有的设备
Console.WriteLine("设备列表：",Color.LightBlue);
foreach(var d in Device.GetList())
    Console.WriteLine(d, Color.Yellow);

Console.Write("请输入你要连接设备的完整名称：", Color.White);
var name = Console.ReadLine();

//连设备
if(!device.Connect(name))
{
    Console.WriteLine("连接失败", Color.Red);
    return;
}

//初始化设备
Console.WriteLine("正在初始化设备", Color.White);
var wait = new AutoResetEvent(false);//信号量
device.InitialReceived += (_, _) => wait.Set();//初始化事件触发
while(true)//不断尝试初始化
{
    wait.Reset();
    Device.iot_uart_send_initial();
    var r = wait.WaitOne(2000);
    if (r)
        break;//初始化好了
    else
        Console.WriteLine("重新尝试初始化设备", Color.White);
}

//收到数据的事件
device.DataReceived += (_, data) =>
{
    Console.Write(
        $"\r{data.Average(e=>e.Item1):F4}mA\t{data.Average(e=>e.Item2):F4}V      ",
        Color.Green);
};
